import { useState } from "react";
import { BORDER_COLOR } from "~/constants";
import SettingsIcon from "~/components/icons/SettingsIcon";
import { Modal, ModalContext } from "~/components/modals/Modal";
import { _ } from "~/lib/i18n";
import { APP_VERSION } from "~/version";

const barStyle = {
  display: "flex",
  flexDirection: "row" as "row",
  alignItems: "center",
  justifyContent: "space-between",
  padding: "0.4em 0.8em",
  borderBottom: "1px solid " + BORDER_COLOR,
  position: "sticky" as "sticky",
  top: 0,
  backgroundColor: "rgba(24, 24, 33, 0.7)",
  backdropFilter: "blur(10px)",
  zIndex: 99,
};

const iconStyle = {
  width: "1.4em",
  height: "auto",
  cursor: "pointer",
};

const buttonStyle = {
  padding: "0.3em 0.8em",
  border: "1px solid #444",
  backgroundColor: "transparent",
  color: "white",
  cursor: "pointer",
};

const activeButtonStyle = {
  ...buttonStyle,
  backgroundColor: "#444",
};

interface Props {
  children: React.ReactNode;
}

export default function TitleBar({ children }: Props) {
  const [showSettings, setShowSettings] = useState(false);
  const [displayMode, setDisplayMode] = useState<"default" | "compact">("default");

  // 暂时隐藏导入导出功能，保留函数定义以备将来使用
  /*
  const exportData = useCallback(async () => {
    try {
      // 获取所有数据
      const posts = await db.posts.orderBy("active").reverse().toArray();
      const replies = await db.replies.toArray();
      const likes = await db.likes.toArray();
      
      // 创建导出数据对象
      const exportData = {
        version: APP_VERSION,
        exportDate: new Date().toISOString(),
        data: {
          posts,
          replies,
          likes
        }
      };
      
      // 创建ZIP文件
      const zip = new JSZip();
      zip.file("data.json", JSON.stringify(exportData, null, 2));
      
      // 生成ZIP并下载
      const blob = await zip.generateAsync({ type: "blob" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `justsocial-export-${new Date().toISOString().slice(0, 10)}.zip`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch (error) {
      console.error(_("Export Error") + ":", error);
      alert(_("Export Error"));
    }
  }, []);

  const importData = useCallback(() => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = ".zip";
    
    input.onchange = async (event) => {
      try {
        const file = (event.target as HTMLInputElement).files?.[0];
        if (!file) return;
        
        // 解压ZIP文件
        const zip = new JSZip();
        const zipContent = await zip.loadAsync(file);
        const dataFile = zipContent.file("data.json");
        
        if (!dataFile) {
          throw new Error("ZIP文件中未找到data.json");
        }
        
        const text = await dataFile.async("text");
        const importData = JSON.parse(text);
        
        // 确认导入
        if (!confirm(`${_("Confirm Import")}

${_("Import Info")}
${_("Version Label")}：${importData.version}
${_("Export Time")}：${importData.exportDate}`)) {
          return;
        }
        
        // 导入数据
        const { posts, replies, likes } = importData.data;
        
        // 清空现有数据
        await db.posts.clear();
        await db.replies.clear();
        await db.likes.clear();
        
        // 导入新数据
        if (posts && posts.length > 0) {
          await db.posts.bulkAdd(posts);
        }
        
        if (replies && replies.length > 0) {
          await db.replies.bulkAdd(replies);
        }
        
        if (likes && likes.length > 0) {
          await db.likes.bulkAdd(likes);
        }
        
        alert(_("Import Success"));
        window.location.reload();
      } catch (error) {
        console.error(_("Import Error") + ":", error);
        alert(_("Import Error"));
      }
    };
    
    document.body.appendChild(input);
    input.click();
    document.body.removeChild(input);
  }, []);
  */

  const handleModeChange = (mode: "default" | "compact") => {
    setDisplayMode(mode);
    // 这里可以添加保存设置到 localStorage 的逻辑
    // localStorage.setItem('displayMode', mode);
  };

  return (
    <>
      <div style={barStyle}>
        <div style={{ display: "flex", alignItems: "center", gap: "0.5em" }}>
          <SettingsIcon 
            style={iconStyle} 
            onClick={() => setShowSettings(true)}
          />
        </div>
        {children}
      </div>

      <ModalContext.Provider value={{ isOpen: showSettings, setOpen: setShowSettings }}>
        <Modal>
          <div style={{ padding: "1em", minWidth: "200px" }}>
            <h3>{_("Settings")}</h3>
            <div style={{ 
              display: "flex", 
              flexDirection: "column",
              gap: "0.5em",
              marginTop: "1em"
            }}>
              {/* 隐藏导入导出功能，直到问题解决 */}
              {/* <button onClick={exportData}>{_("Export Data")}</button>
              <button onClick={importData}>{_("Import Data")}</button> */}
              <div>
                <div>{_("Display Mode")}:</div>
                <div style={{ display: "flex", gap: "1em", marginLeft: "1em", marginTop: "0.5em" }}>
                  <button 
                    style={displayMode === "default" ? activeButtonStyle : buttonStyle}
                    onClick={() => handleModeChange("default")}
                  >
                    {_("Default")}
                  </button>
                  <button 
                    style={displayMode === "compact" ? activeButtonStyle : buttonStyle}
                    onClick={() => handleModeChange("compact")}
                  >
                    {_("Compact")}
                  </button>
                </div>
              </div>
              <div style={{ 
                marginTop: "0.5em", 
                paddingTop: "0.5em", 
                borderTop: "1px solid #444" 
              }}>
                <small>{_("Version")}: {APP_VERSION}</small>
              </div>
            </div>
          </div>
        </Modal>
      </ModalContext.Provider>
    </>
  );
}